<?php

namespace app\api\biz;

use app\common\biz\Biz;
use app\common\biz\list\Lists;
use app\common\biz\list\Search;
use app\common\biz\list\SearchType;
use app\common\enum\Code;
use app\common\enum\SearchType as SearchTypeEnum;
use app\common\model\biz\SysRole;
use app\common\Result;
use Exception;
use think\db\exception\DbException;

class RoleBiz extends Biz
{

    public static function list(array $searchParams = []): RoleBiz
    {
        $searchType = new SearchType();
        $searchType->set('name', SearchTypeEnum::Like);
        $search = new Search($searchParams, $searchType);

        $lists = new Lists(new SysRole(), $search);
        return self::success($lists->data());
    }

    public static function add(array $data): RoleBiz
    {
        try {
            $role = SysRole::where('name', $data['name'])
                ->findOrEmpty();
            if (!$role->isEmpty()) {
                return self::error('此角色已存在！');
            }

            $role = SysRole::create($data);
            return self::success($role);
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }

    public static function edit(array $data): RoleBiz
    {
        if (!isset($data['id']) || !isset($data['name'])) {
            return self::errorByCode(Code::ParamsInvalid);
        }

        try {
            $role = SysRole::findOrEmpty($data['id']);
            if ($role->isEmpty()) {
                return self::errorByCode(Code::DataNotFound);
            }
            $isExist = SysRole::where('name', $data['name'])
                ->where('id', '<>', $data['id'])
                ->findOrEmpty();
            if (!$isExist->isEmpty()) {
                return self::error('此角色已存在！');
            }

            $isOk = $role->save($data);
            return self::success($isOk);
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }

    public static function del(string|array $ids): RoleBiz
    {
        $roles = SysRole::whereIn('id', $ids)->select();
        if ($roles->isEmpty()) {
            return self::errorByCode(Code::DataNotFound);
        }

        foreach ($roles as $role) {
            $role->delete();
        }

        return self::success();

    }
}